package com.ruoyi.web.service;

import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.web.vo.CreatePicForm;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;

@Slf4j
@Service
public class ToolsService {

    public String createPic(CreatePicForm createPicForm) {
        try {
            String type = createPicForm.getType();
            String x = createPicForm.getX();
            String y = createPicForm.getY();
            String xx = createPicForm.getXx();
            String yy = createPicForm.getYy();
            String picName = String.format("%s.jpg", DateUtils.getTimeStamp());
            StringBuilder cmd = new StringBuilder(String.format("/usr/bin/python3 pyScripts%sCreatePic.py \"%s\" \"%s\" \"%s\" \"%s\" \"%s\" \"%s\"", File.separator, type, x, y, xx, yy, picName));
            for (String i : createPicForm.getLine().split("\\|")) {
                if (StringUtils.isNotEmpty(i)) {
                    cmd.append(" \"").append(i).append("\"");
                }
            }
            log.info(cmd.toString());
            Process exec = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd.toString()});
            BufferedReader b = new BufferedReader(new InputStreamReader(exec.getInputStream()));
            String s;
            StringBuilder ss = new StringBuilder();
            while ((s = b.readLine()) != null) {
                ss.append(s);
            }
            b.close();
            exec.waitFor();
            if (ss.toString().contains("失败")) {
                return ss.toString();
            } else {
                log.info(ss.toString());
                return picName;
            }
        } catch (Exception e) {
            return String.format("失败:%s", e);
        }
    }
}
